package com.spring.sunflower.conversation;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGAImageView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.spring.sunflower.App;
import com.spring.sunflower.R;
import com.spring.sunflower.anchor.PersonalDetailActivity;
import com.spring.sunflower.base.BaseActivity;
import com.spring.sunflower.bean.AccountBean;
import com.spring.sunflower.bean.AnchorDetailBean;
import com.spring.sunflower.bean.CustomMessageBean;
import com.spring.sunflower.bean.MessageCustomEntity;
import com.spring.sunflower.bean.MessageEntity;
import com.spring.sunflower.bean.STSCertBean;
import com.spring.sunflower.bottompanel.EmotionMainFragment;
import com.spring.sunflower.bottompanel.OnBottomPanelShowListener;
import com.spring.sunflower.common.FileUploadCallback;
import com.spring.sunflower.common.PhotoViewerActivity;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.dialog.CustomerDialog;
import com.spring.sunflower.dialog.DialogManager;
import com.spring.sunflower.dialog.FollowedDialog;
import com.spring.sunflower.dialog.OnPermissionIntroClickListener;
import com.spring.sunflower.event.BaseChatEvent;
import com.spring.sunflower.event.GiftSendEvent;
import com.spring.sunflower.event.GiftSendSuccessEvent;
import com.spring.sunflower.event.ImageSendSuccessEvent;
import com.spring.sunflower.event.LastChatEvent;
import com.spring.sunflower.event.VideoCallOverEvent;
import com.spring.sunflower.event.VoiceSendSuccessEvent;
import com.spring.sunflower.util.AliUploadUtils;
import com.spring.sunflower.util.AppUtils;
import com.spring.sunflower.util.AudioUtils;
import com.spring.sunflower.util.LogUtils;
import com.spring.sunflower.util.PathUtils;
import com.spring.sunflower.util.SPUtils;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMCustomElem;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMMessageListGetOption;
import com.tencent.imsdk.v2.V2TIMSendCallback;
import com.tencent.imsdk.v2.V2TIMValueCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * Created by Kevin on 2021/6/5<br/>
 * <p>
 * Describe:<br/>
 */
public class ChatActivity extends BaseActivity<ChatPresenter> implements ConversationView, OnRefreshListener, View.OnClickListener, TextWatcher, OnBottomPanelShowListener {
    private SmartRefreshLayout refreshLayout;
    private static RecyclerView mRecyclerView;
    private ImageView mSend;
    private EditText mEditText;
    private LinearLayout llContainer;
    private TextView tvTitle;
    private ImageView ivVoice, ivImage, ivVideo, ivEmoji, ivGift;
    private List<MessageCustomEntity> messageList = new ArrayList<>();
    //    private List<V2TIMMessage> messageList = new ArrayList<>();
    private List<MessageCustomEntity> messageListTemp = new ArrayList<>();
    //    private List<V2TIMMessage> messageListTemp = new ArrayList<>();
    private static ChatCustomAdapter mAdapter;
    //    private ConversationAdapterX mAdapter;
    private int mScreenHeight;
    private boolean mPendingShowPlaceHolder;
    private Rect mTmpRect = new Rect();
    public static String mOtherUserID;
    private int msgCount = 20;
    private V2TIMMessage lastV2TIMMessage = null;
    private V2TIMMessage newestV2TIMMessage = null;
    private FrameLayout flBottomBoard;
    private boolean keyboardShow = false;
    private BottomPanelFragment bottomPanelFragment;
    private EmotionMainFragment emotionMainFragment;
    private String mOtherShowName;
    private String mOtherFaceUrl;
    private String mSelfUserID;
    private String mSelfAvatar;
    private String mSelfNickname;
    private CustomMessageBean.DataBean data;
    private AliUploadUtils aliUploadUtils;
    private AudioUtils audioUtils;
    private String keyID = "", keySecret = "", securityToken = "";
    private AnimationDrawable animationDrawable;
    private SVGAImageView mSVGAPlayer;
    private boolean isShowCamera = mGrantedCameraPermission;
    private boolean mHasBlacked;
    private List<String> svgaSource = new ArrayList<>();
    private boolean isFromHelp = false;
    private boolean shouldRefreshMsgOnResume = false;//执行过onStop再回来的时候刷新，解决app从聊天页面点击home键退到后台再回来不刷新的问题
    private long currentTimeMillis;
    public static ChatActivity getSingleton = null;
    SVGACallback svgaCallback = new SVGACallback() {

        @Override
        public void onStep(int frame, double percentage) {

        }

        @Override
        public void onRepeat() {

        }

        @Override
        public void onPause() {

        }

        @Override
        public void onFinished() {
            if (svgaSource.size() > 1) {
                svgaSource.remove(0);
                String s = svgaSource.get(0);
                ConversationManager.playSVGA(ChatActivity.this, mSVGAPlayer, s);
            } else if (svgaSource.size() > 0) {
                svgaSource.remove(0);
            }
        }
    };

    @Override
    public void doSomethingBeforeOnCreate() {
        super.doSomethingBeforeOnCreate();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    public void initView() {
        this.getSingleton = this;
        flBottomBoard = findViewById(R.id.fl_bottom_board);
        Intent intent = getIntent();
        isFromHelp = intent.getBooleanExtra(Constant.IS_FROM_HELP, false);
        String conversationId = intent.getStringExtra(Constant.C2C_CONVERSATION_ID);
        mOtherUserID = intent.getStringExtra(Constant.C2C_USER_ID);
        mOtherShowName = intent.getStringExtra(Constant.C2C_SHOW_NAME);
        mOtherFaceUrl = intent.getStringExtra(Constant.C2C_FACE_URL);
        mSelfUserID = getField(Constant.KEY_USERID, "");
        mSelfAvatar = getField(Constant.KEY_PHOTO, "");
        mSelfNickname = getField(Constant.KEY_NICKNAME, "");

        saveField(Constant.KEY_USERID_CHATTER, mOtherUserID);
        saveField(Constant.KEY_AVATAR_CHATTER, mOtherFaceUrl);
        saveField(Constant.KEY_NICKNAME_CHATTER, mOtherShowName);
        printD("otherUserID=" + mOtherUserID);
//        showToast(mOtherUserID);
        audioUtils = AudioUtils.getInstance();

        tvFunctionX.setText(getString(R.string.font_more));
        tvFunctionX.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f);
        AppUtils.setFont(this, tvFunctionX);
        if (isFromHelp) {
            tvFunctionX.setVisibility(View.GONE);
        } else {
            tvFunctionX.setVisibility(View.VISIBLE);
        }
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText(mOtherShowName);
        refreshLayout = findViewById(R.id.refreshLayout);
        mRecyclerView = findViewById(R.id.rvRecyclerView);
        llContainer = findViewById(R.id.llContainer);
        mSVGAPlayer = findViewById(R.id.svgaPlayer);
        mSVGAPlayer.setCallback(svgaCallback);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setOnRefreshListener(this);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new ChatCustomAdapter(messageList);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                if (e.getAction() == MotionEvent.ACTION_DOWN) {
                    KeyboardUtils.hideSoftInput(ChatActivity.this);
                    if (EmotionMainFragment.emotionLayout != null) {
                        EmotionMainFragment.emotionLayout.setVisibility(View.GONE);
                    }
                    EmotionMainFragment.ivEmoji.setImageResource(R.drawable.ic_more_emoji);
                }
                return super.onInterceptTouchEvent(rv, e);
            }
        });

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (isFastClick()) return;
                if (audioUtils.isPlay()) {
                    if (null != animationDrawable && animationDrawable.isRunning())
                        animationDrawable.stop();
                    animationDrawable.selectDrawable(2);
                    audioUtils.stopPlay();
                    return;
                }
                handleItemClick(adapter, position);
            }
        });
        mAdapter.addChildClickViewIds(R.id.user_icon_left, R.id.user_icon_right);
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (isFastClick()) return;
                switch (view.getId()) {
                    case R.id.user_icon_left:
                        if (mOtherUserID.equals(Constant.OFFICIAL_USER_ID_SERVICE)) {
                            showToast(getString(R.string.official_service) + "正在和您对话中...");
                            return;
                        }
                        Intent intent = new Intent(ChatActivity.this, PersonalDetailActivity.class);
                        intent.putExtra(Constant.KEY_TARGET_ID, mOtherUserID);
                        startActivity(intent);
                        break;
                    case R.id.user_icon_right:
                        Intent intent1 = new Intent(ChatActivity.this, PersonalDetailActivity.class);
                        intent1.putExtra(Constant.KEY_TARGET_ID, mSelfUserID);
                        startActivity(intent1);
                        break;
                }

            }
        });
        getMsgHistory(null);
//        getMsgHistoryList(null, true);
//        V2TIMManager.getMessageManager().addAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
//            @Override
//            public void onRecvNewMessage(V2TIMMessage msg) {
//                super.onRecvNewMessage(msg);
//                printD("onRecvNewMessage");
//                refreshChatList(msg, false);
//            }
//
//            @Override
//            public void onRecvC2CReadReceipt(List<V2TIMMessageReceipt> receiptList) {
//                super.onRecvC2CReadReceipt(receiptList);
//            }
//
//            @Override
//            public void onRecvMessageRevoked(String msgID) {
//                super.onRecvMessageRevoked(msgID);
//            }
//        });
        initEmotionFragment();
        mPresenter.getSTSCert();
        mPresenter.getHasFollowed(mOtherUserID);
//        mPresenter.getAnchorDetail(mOtherUserID);
        tvFunctionX.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChatActivity.this, ChatCommentActivity.class);
                intent.putExtra("otherAvatar", mOtherFaceUrl);
                intent.putExtra("otherNickname", mOtherShowName);
                intent.putExtra("otherUserId", mOtherUserID);
                intent.putExtra("userId", mSelfUserID);
                startActivity(intent);
            }
        });

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        printD("onNewIntent");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (shouldRefreshMsgOnResume) {
//            getMsgHistoryList(newestV2TIMMessage, true);
////            getMsgHistory(lastV2TIMMessage);
//            shouldRefreshMsgOnResume = false;
//            currentTimeMillis = System.currentTimeMillis();
//            printD("onResume=" + currentTimeMillis);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        printD("onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        printD("onStop");
        shouldRefreshMsgOnResume = true;
    }

    private void handleItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, int position) {
        MessageCustomEntity messageCustomEntity = messageList.get(position);
        if (MessageCustomEntity.MSG_TYPE_AUDIO == messageCustomEntity.getItemType()) {
            String audioUrl = messageCustomEntity.getAudioUrl();
            ImageView iv;
            if (messageCustomEntity.isSelf()) {
                iv = (ImageView) adapter.getViewByPosition(position, R.id.iv_audio_play_right);
                iv.setImageResource(R.drawable.play_voice_message);
                iv.setRotation(180);
            } else {
                iv = (ImageView) adapter.getViewByPosition(position, R.id.iv_audio_play_left);
                iv.setImageResource(R.drawable.play_voice_message);
            }
            animationDrawable = (AnimationDrawable) iv.getDrawable();
            animationDrawable.start();
            audioUtils.play(audioUrl, new AudioUtils.PlayCallBack() {
                @Override
                public void onCompletion(MediaPlayer param1MediaPlayer) {
                    if (null != animationDrawable && animationDrawable.isRunning()) {
                        animationDrawable.stop();
                        animationDrawable.selectDrawable(2);
                        animationDrawable = null;
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        iv.setImageResource(R.drawable.msg_voice_playing_3);
//                                        if (messageCustomEntity.isSelf()) {
//                                            iv.setRotation(180);
//                                        }
//
//                                    }
//                                });
                    }
                }

                @Override
                public void onPrepared(MediaPlayer param1MediaPlayer) {

                }
            });
        } else if (MessageCustomEntity.MSG_TYPE_IMAGE == messageCustomEntity.getItemType()) {
            String picUrl = messageCustomEntity.getPicUrl();
            ArrayList<String> list = new ArrayList<>();
            for (MessageCustomEntity entity : messageList) {
                if (entity.getItemType() == MessageCustomEntity.MSG_TYPE_IMAGE) {
                    list.add(entity.getPicUrl());
                }
            }
            int i = list.indexOf(picUrl);
            Intent intent = new Intent(ChatActivity.this, PhotoViewerActivity.class);
            intent.putStringArrayListExtra(Constant.PHOTO_LIST_VIEWER, list);
            intent.putExtra(Constant.PHOTO_CURRENT_POSITION, i);
            startActivity(intent);

        }
    }

    private void initEmotionFragment() {
        //构建传递参数
        Bundle bundle = new Bundle();
        bundle.putBoolean(Constant.IS_FROM_HELP, isFromHelp);
//        //绑定主内容编辑框
//        bundle.putBoolean(BottomPanelFragment.BIND_TO_EDITTEXT, true);
//        //隐藏控件
//        bundle.putBoolean(BottomPanelFragment.HIDE_BAR_EDITTEXT_AND_BTN, false);
        //替换fragment
        //创建修改实例
        emotionMainFragment = EmotionMainFragment.newInstance(bundle);
        emotionMainFragment.setOnBottomPanelShowListener(this);
        emotionMainFragment.bindToContentView(llContainer);
//        bottomPanelFragment = BottomPanelFragment.newInstance(bundle);
//        bottomPanelFragment.bindToContentView(mRecyclerView);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in thefragment_container view with this fragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fl_bottom_board, emotionMainFragment);
        transaction.addToBackStack(null);
//        //提交修改
        transaction.commit();
//        bottomPanelFragment.addOnBottomPanelListener(this);
    }

    @Override
    public void onBackPressed() {
        if (emotionMainFragment != null && !emotionMainFragment.isInterceptBackPress()) {
            finish();
        }
    }

    private void getMsgHistory(V2TIMMessage lastMsg) {
        printD("getMsgHistory" + lastMsg);
//        String userID = getField(Constant.KEY_USERID_CHATTER, "");
        V2TIMMessageListGetOption v2TIMMessageListGetOption = new V2TIMMessageListGetOption();
        v2TIMMessageListGetOption.setCount(msgCount);
        v2TIMMessageListGetOption.setLastMsg(lastMsg);
        v2TIMMessageListGetOption.setUserID(mOtherUserID);
        V2TIMManager.getMessageManager().getC2CHistoryMessageList(mOtherUserID, msgCount, lastMsg, new V2TIMValueCallback<List<V2TIMMessage>>() {
            @Override
            public void onError(int i, String s) {
                if (refreshLayout.isRefreshing()) {
                    refreshLayout.finishRefresh();
                }
                showToast("获取失败code:" + i + ",msg=" + s);
            }

            @Override
            public void onSuccess(List<V2TIMMessage> v2TIMMessages) {
                if (v2TIMMessages.size() > 0) {
                    lastV2TIMMessage = v2TIMMessages.get(v2TIMMessages.size() - 1);
                    newestV2TIMMessage = v2TIMMessages.get(0);
                    V2TIMCustomElem customElem1 = lastV2TIMMessage.getCustomElem();
                    byte[] data1 = customElem1.getData();
                    String s1 = new String(data1);
                    printI("contentxxxx=" + s1);
                    for (int i = 0; i < v2TIMMessages.size(); i++) {
                        V2TIMCustomElem customElem = v2TIMMessages.get(i).getCustomElem();
                        byte[] data = customElem.getData();
                        String s = new String(data);
                        printW("content==" + s);
                    }
                    List<MessageCustomEntity> messageEntities = processMessageList(v2TIMMessages, true);
                    for (int i = 0; i < messageEntities.size(); i++) {
                        String content = messageEntities.get(i).getContent();
                        printI("content=" + content);
                    }
                    if (mAdapter == null) {
                        printE("mAdapter is null");
                    } else {
                        printE("mAdapter is not null");
                    }
                    mAdapter.addData(0, messageEntities);
                    if (lastMsg == null) {
                        scrollToEnd();
                    }
                    if (refreshLayout.isRefreshing()) {
                        refreshLayout.finishRefresh();
                    }
                }else{
                    if (refreshLayout.isRefreshing()) {
                        refreshLayout.finishRefresh();
                    }
                }
            }
        });
    }

    /**
     * 获取消息记录
     *
     * @param lastMsg
     * @param newerMsg true为更新的，false为更老的
     */
    private void getMsgHistoryList(V2TIMMessage lastMsg, boolean newerMsg) {
        if (lastMsg != null) {
            V2TIMCustomElem customElem = lastMsg.getCustomElem();
            byte[] data = customElem.getData();
            String s = new String(data);
            printI("s=" + s);
        }
//        String userID = getField(Constant.KEY_USERID_CHATTER, "");
        V2TIMMessageListGetOption v2TIMMessageListGetOption = new V2TIMMessageListGetOption();
        v2TIMMessageListGetOption.setCount(msgCount);
//        if (lastMsg != null) {
        v2TIMMessageListGetOption.setLastMsg(lastMsg);
//        }
        v2TIMMessageListGetOption.setUserID(mOtherUserID);
        if (currentTimeMillis > 0) {
            v2TIMMessageListGetOption.setGetTimeBegin(currentTimeMillis / 1000);
        }
        if (newerMsg) {
            v2TIMMessageListGetOption.setGetType(V2TIMMessageListGetOption.V2TIM_GET_LOCAL_NEWER_MSG);
        } else {
            v2TIMMessageListGetOption.setGetType(V2TIMMessageListGetOption.V2TIM_GET_LOCAL_OLDER_MSG);
        }
        V2TIMManager.getMessageManager().getHistoryMessageList(v2TIMMessageListGetOption, new V2TIMValueCallback<List<V2TIMMessage>>() {
            @Override
            public void onSuccess(List<V2TIMMessage> v2TIMMessages) {
                printE("v2TIMMessages===" + v2TIMMessages.size());
                if (v2TIMMessages.size() > 0) {
                    newestV2TIMMessage = v2TIMMessages.get(v2TIMMessages.size() - 1);
                    for (int i = 0; i < v2TIMMessages.size(); i++) {
                        V2TIMCustomElem customElem = v2TIMMessages.get(i).getCustomElem();
                        byte[] data = customElem.getData();
                        String s = new String(data);
                        printW("content==" + s);
                    }
                    List<MessageCustomEntity> messageEntities = processMessageList(v2TIMMessages, newerMsg ? false : true);

                    if (mAdapter == null) {
                        printE("mAdapter is null");
                    } else {
                        printE("mAdapter is not null");
                    }
                    if (newerMsg) {
                        mAdapter.addData(messageEntities);
                        scrollToEnd();
                    } else {
                        mAdapter.addData(0, messageEntities);
                    }
                    if (refreshLayout.isRefreshing()) {
                        refreshLayout.finishRefresh();
                    }
                    V2TIMManager.getMessageManager().markC2CMessageAsRead(mOtherUserID, new V2TIMCallback() {
                        @Override
                        public void onError(int code, String desc) {

                        }

                        @Override
                        public void onSuccess() {

                        }
                    });
                }else{
                    if (refreshLayout.isRefreshing()) {
                        refreshLayout.finishRefresh();
                    }
                }

            }

            @Override
            public void onError(int code, String desc) {

            }
        });
    }

    private boolean isKeyboardVisible() {
        int DISTANCE_SLOP = 180;
        return (mScreenHeight - getInputBottom() > DISTANCE_SLOP);
    }

    /**
     * 输入框下边的位置
     */
    private int getInputBottom() {
//        llBottomContainer.getGlobalVisibleRect(mTmpRect);
        return mTmpRect.bottom;
    }

    public static ChatCustomAdapter getAdapter() {
        return mAdapter;
    }

    public void refreshChatList(List<V2TIMMessage> msg, boolean isSend) {
//        MessageEntity messageEntity = V2TIMMessageConvertToMessageEntity(msg);
        List<MessageCustomEntity> messageCustomEntityList = new ArrayList<>();
        for (V2TIMMessage message : msg) {
            CustomMessageBean bean = ConversationManager.processV2TIMMessage(message);
            if (isSend) {
                MessageCustomEntity messageCustomEntity = ConversationManager.customMessageBean2MessageCustomEntity(bean, message);
                if (messageCustomEntity != null) {
                    messageCustomEntityList.add(messageCustomEntity);
                }
            } else {
                if (bean != null) {
                    if (bean.data != null) {
                        if (bean.data.fromUser.memberId.equals(mOtherUserID) || bean.data.msgType.equals(Constant.CUSTOM_MESSAGE_LOCAL_TIME)) {
                            MessageCustomEntity messageCustomEntity = ConversationManager.customMessageBean2MessageCustomEntity(bean, message);
                            if (messageCustomEntity != null) {
                                messageCustomEntityList.add(messageCustomEntity);
                            }
                        } else {
                        }
                    }
                }
            }
        }
        mAdapter.addData(messageCustomEntityList);
        scrollToEnd();
    }

    public void refreshChatList(V2TIMMessage msg, boolean isSend) {
//        MessageEntity messageEntity = V2TIMMessageConvertToMessageEntity(msg);
        CustomMessageBean bean = ConversationManager.processV2TIMMessage(msg);
        if (isSend) {
            MessageCustomEntity messageCustomEntity = ConversationManager.customMessageBean2MessageCustomEntity(bean, msg);
            if (messageCustomEntity != null) {
                mAdapter.addData(messageCustomEntity);
                scrollToEnd();
            }
        } else {
            if (bean != null) {
                if (bean.data != null) {
                    if (bean.data.fromUser.memberId.equals(mOtherUserID)) {
                        MessageCustomEntity messageCustomEntity = ConversationManager.customMessageBean2MessageCustomEntity(bean, msg);
                        if (messageCustomEntity != null) {
                            mAdapter.addData(messageCustomEntity);
                            scrollToEnd();
                        }
                    } else {
                    }
                }
            }
        }
    }

    public static void scrollToEnd() {
        if (mRecyclerView != null) {
            LogUtils.INSTANCE.logD("ChatActivity", "mAdapter.getItemCount() =" + mAdapter.getItemCount());
            mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
        } else {
            LogUtils.INSTANCE.logD("ChatActivity", "recyclerview is null");
        }
    }

    private List<MessageCustomEntity> processMessageList(List<V2TIMMessage> v2TIMMessages, boolean isReverse) {
        messageListTemp.clear();
        if (isReverse) {
            Collections.reverse(v2TIMMessages);
        }
        for (V2TIMMessage v : v2TIMMessages) {
            CustomMessageBean bean = ConversationManager.processV2TIMMessage(v);
            if (bean != null) {
                MessageCustomEntity messageCustomEntity = ConversationManager.customMessageBean2MessageCustomEntity(bean, v);
                messageListTemp.add(messageCustomEntity);
            }
        }
        return messageListTemp;
    }

    private MessageCustomEntity customMessageBean2MessageCustomEntity(CustomMessageBean customMessageBean, V2TIMMessage msg) {
        data = customMessageBean.data;
        if (data == null) return null;
        String msgType = data.msgType;
        MessageCustomEntity messageCustomEntity = new MessageCustomEntity();
        switch (msgType) {
            case Constant.CUSTOM_MESSAGE_TEXT:
                messageCustomEntity.setItemType(MessageCustomEntity.MSG_TYPE_TEXT);
                break;
            case Constant.CUSTOM_MESSAGE_GIFT:
                messageCustomEntity.setItemType(MessageCustomEntity.MSG_TYPE_CUSTOM_GIFT);
                if (data.gift != null) {
                    if (data.gift.imagePath != null) {
                        messageCustomEntity.setGiftImagePath(data.gift.imagePath);
                    }
                    if (data.gift.effects != null) {
                        messageCustomEntity.setGiftEffects(data.gift.effects);
                    }
                    if (data.gift.name != null) {
                        messageCustomEntity.setGiftName(data.gift.name);
                    }
                    if (data.gift.number != null) {
                        messageCustomEntity.setGiftNumber(data.gift.number);
                    }
                }
                break;
            case Constant.CUSTOM_MESSAGE_SOUND:
                messageCustomEntity.setItemType(MessageCustomEntity.MSG_TYPE_AUDIO);
                messageCustomEntity.setAudioUrl(data.audio.url);
                messageCustomEntity.setAudioDuration(data.audio.duration);
                break;
            case Constant.CUSTOM_MESSAGE_PICTURE:
                messageCustomEntity.setItemType(MessageCustomEntity.MSG_TYPE_IMAGE);
                if (data.picture != null) {
                    messageCustomEntity.setPicUrl(data.picture.url);
                    messageCustomEntity.setPicWidth(data.picture.width);
                    messageCustomEntity.setPicHeight(data.picture.height);
                }
                break;
            case Constant.CUSTOM_MESSAGE_SYSTEM:
                break;
            case Constant.CUSTOM_MESSAGE_VIDEO_CALL:
                messageCustomEntity.setItemType(MessageCustomEntity.MSG_TYPE_CUSTOM);
                break;
        }
        messageCustomEntity.setContent(data.content);

        String fromUserPhoto = msg.isSelf() ? mSelfAvatar : mOtherFaceUrl;
        String fromUserNickname = data.fromUser.getNickname();
        String fromUserMemberId = data.fromUser.getMemberId();
        String toUserPhoto = data.toUser.getPhoto();
        String toUserMemberId = data.toUser.getMemberId();
        String toUserNickname = data.toUser.getNickname();
        messageCustomEntity.setFromUserMemberId(fromUserMemberId);
        messageCustomEntity.setFromUserNickname(fromUserNickname);
        messageCustomEntity.setFromUserPhoto(fromUserPhoto);
        messageCustomEntity.setToUserMemberId(toUserMemberId);
        messageCustomEntity.setToUserNickname(toUserNickname);
        messageCustomEntity.setToUserPhoto(toUserPhoto);
        printD("fromUserPhoto=" + fromUserPhoto + ",   toUserPhoto   " + toUserPhoto);
        messageCustomEntity.setMsgID(msg.getMsgID());
        messageCustomEntity.setRandom(msg.getRandom());
        messageCustomEntity.setSelf(msg.isSelf());
        messageCustomEntity.setStatus(msg.getStatus());
        messageCustomEntity.setTimestamp(msg.getTimestamp());
        messageCustomEntity.setSeq(msg.getSeq());
        return messageCustomEntity;
    }


    @NotNull
    private MessageEntity V2TIMMessageConvertToMessageEntity(V2TIMMessage v2TIMMessage) {
        int elemType = v2TIMMessage.getElemType();
        MessageEntity messageEntity = new MessageEntity(elemType);
        switch (elemType) {
            case V2TIMMessage.V2TIM_ELEM_TYPE_TEXT:
                messageEntity.setTextElem(v2TIMMessage.getTextElem());
                break;
            case V2TIMMessage.V2TIM_ELEM_TYPE_IMAGE:
                messageEntity.setImageElem(v2TIMMessage.getImageElem());
                break;
            case V2TIMMessage.V2TIM_ELEM_TYPE_SOUND:
                messageEntity.setSoundElem(v2TIMMessage.getSoundElem());
                break;
            case V2TIMMessage.V2TIM_ELEM_TYPE_VIDEO:
                messageEntity.setVideoElem(v2TIMMessage.getVideoElem());
                break;
            case V2TIMMessage.V2TIM_ELEM_TYPE_LOCATION:
                messageEntity.setLocationElem(v2TIMMessage.getLocationElem());
                break;
        }
        messageEntity.setFaceUrl(v2TIMMessage.getFaceUrl());
        messageEntity.setTimestamp(v2TIMMessage.getTimestamp());
        messageEntity.setSender(v2TIMMessage.getSender());
        messageEntity.setSelf(v2TIMMessage.isSelf());
        messageEntity.setStatus(v2TIMMessage.getStatus());
        messageEntity.setMsgID(v2TIMMessage.getMsgID());
        messageEntity.setUserID(v2TIMMessage.getUserID());
        messageEntity.setRead(v2TIMMessage.isRead());
        messageEntity.setOfflinePushINfo(v2TIMMessage.getOfflinePushInfo());
        messageEntity.setNickName(v2TIMMessage.getNickName());
        messageEntity.setFriendRemark(v2TIMMessage.getFriendRemark());
        return messageEntity;
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_chat;
    }

    @Override
    public ChatPresenter setPresenter() {
        return new ChatPresenter(this);
    }

    @Override
    public boolean shouldRegisterEventBus() {
        return true;
    }

    @Override
    public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
//        MessageEntity messageEntity = mAdapter.getData().get(0);
//        getMsgHistory(lastV2TIMMessage);
        getMsgHistoryList(lastV2TIMMessage, false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }


    private void showSoftInput(View view) {
        keyboardShow = true;
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, 0);
    }

    private void hideSoftInput(View view) {
        keyboardShow = false;
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    @Override
    public void loadSTSCert(STSCertBean.DatasBean data) {
        keyID = data.getAccessKeyId();
        keySecret = data.getAccessKeySecret();
        securityToken = data.getSecurityToken();
        saveField(Constant.STS_KEY_ID, keyID);
        saveField(Constant.STS_KEY_SECRET, keySecret);
        saveField(Constant.STS_SECURITY_TOKEN, securityToken);
        aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken);
    }

    @Override
    public void liveApplySuccess() {
//        String userID = getField(Constant.KEY_USERID_CHATTER, "");
        Intent intent = new Intent(this, ChatVideoActivity.class);
        intent.putExtra(Constant.VIDEO_CALL_SELF_DIAL, true);
        intent.putExtra(Constant.VIDEO_CALL_OTHER_ID, mOtherUserID);
        intent.putExtra(Constant.VIDEO_CALL_OTHER_FACE_URL, mOtherFaceUrl);
        intent.putExtra(Constant.VIDEO_CALL_OTHER_NICKNAME, mOtherShowName);
        intent.putExtra(Constant.VIDEO_CALL_SHOW, false);
        startActivity(intent);
    }

    @Override
    public void hasBlacked(boolean hasBlacked) {
        mHasBlacked = hasBlacked;
    }

    @Override
    public void showAccount(AccountBean.DatasBean data) {
        String money = data.getMoney();
        saveField(Constant.KEY_MONEY, money);
    }

    @Override
    public void showAnchorData(AnchorDetailBean.DatasBean data) {
        String price = data.getPrice();
        saveField(Constant.KEY_CHATTER_PRICE, price);
    }

    @Override
    public void hasFollowed(boolean hasFollowed) {
        boolean hasSave = getField(Constant.KEY_SHOW_FOLLOWED_DIALOG, false);
        if(AppUtils.isVerify(ChatActivity.this)) {
            mPresenter.getVisualizeLabel();
            return;
        }
        if (!hasFollowed && !hasSave) {
            DialogManager.getInstance().showFollowedDialog(this, new FollowedDialog.OnFollowedListener() {
                @Override
                public void onFollowedClick() {
                    mPresenter.setFollowed(mOtherUserID, "1");
                }

                @Override
                public void onFollowedCloseClick() {
                    showNoticeDialog("温馨提醒", "以后不再提示", "选择是以后不会出现关注提醒", "是", "否", new OnPermissionIntroClickListener() {
                        @Override
                        public void onClickCancel() {

                        }

                        @Override
                        public void onClickOK() {
                            saveField(Constant.KEY_SHOW_FOLLOWED_DIALOG, true);
                        }
                    });
//                    showHelpDialog("温馨提示", "关注对方，不错过每个精彩瞬间\n检测到你主动关闭了该窗口,以后不再弹出", null);

                }
            });
        }
    }

    @Override
    public void setFollowedSuccess() {
        showToast("关注成功");
    }

    @Override
    public void setFollowedFailed() {

    }

    @Override
    public void bottomPanelShow() {
        scrollToEnd();
    }

    @Override
    public void bottomPanelHide() {

    }

    @Override
    public void sysKeyboardShow() {
        scrollToEnd();
    }

    @Override
    public void sendClick(String data) {
//        ConversationManager.sendMessage(data, Constant.CUSTOM_MESSAGE_TEXT, new BaseChatEvent(), new V2TIMSendCallback<V2TIMMessage>() {
//            @Override
//            public void onProgress(int progress) {
//
//            }
//
//            @Override
//            public void onError(int code, String desc) {
//                printD("code=" + code + ",desc=" + desc);
//                showToast("发送失败");
//            }
//
//            @Override
//            public void onSuccess(V2TIMMessage v2TIMMessage) {
//                printD("发送成功");
//                refreshChatList(v2TIMMessage, true);
//            }
//        });
        processSendMessage(data, Constant.CUSTOM_MESSAGE_TEXT, new BaseChatEvent());
        if (mOtherUserID.equals(Constant.OFFICIAL_USER_ID_SERVICE)) {
            Random random = new Random();
            int i = random.nextInt(10);

            tvTitle.setText("对方正在输入...");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    tvTitle.setText(getString(R.string.official_service));
                }
            }, i * 500);
        }

    }

    @Override
    public void sendVideoChat() {
//        String userID = getField(Constant.KEY_USERID_CHATTER, "");
        if (!XXPermissions.isGranted(this, Permission.RECORD_AUDIO) || !XXPermissions.isGranted(this, Permission.CAMERA)) {
            showPermissionIntroDialog(new String[]{getString(R.string.permission_audio_title), getString(R.string.permission_camera_title)}, new String[]{getString(R.string.permission_audio_desc), getString(R.string.permission_camera_desc)}, new OnPermissionIntroClickListener() {
                @Override
                public void onClickOK() {
                    XXPermissions.with(ChatActivity.this)
                            .permission(Permission.RECORD_AUDIO, Permission.CAMERA)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    if (all) {
                                        mPresenter.applyChat(mSelfUserID, mOtherUserID);
                                    } else {
                                        showPermissionIntroDialog(getString(R.string.permission_denied_title), "无法正常进行视频通话", null);
                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    showPermissionIntroDialog(getString(R.string.permission_denied_title), "无法正常进行视频通话", null);
                                }
                            });
                }

                @Override
                public void onClickCancel() {

                }
            });
        } else {
            mPresenter.applyChat(mSelfUserID, mOtherUserID);
        }
    }

    @Override
    public void sendImage() {
        checkOpenGallery(this, false);
    }

    public void imageSendSuccess(ImageSendSuccessEvent event) {
        BaseChatEvent<ImageSendSuccessEvent> chatEvent = new BaseChatEvent<>(event);
        processSendMessage("【图片】", Constant.CUSTOM_MESSAGE_PICTURE, chatEvent);
    }

    @Subscribe
    public void refreshMsg(V2TIMMessage message) {
        printD("msg=" + message.toString());
        newestV2TIMMessage = message;
        if (mOtherUserID.equals(Constant.OFFICIAL_USER_ID_SERVICE)) {
            tvTitle.setText(getString(R.string.official_service));
        }
        //收到消息判断当前时间和之前的时间差大于5分钟就添加时间显示
        if (ConversationManager.shouldInsertTime()) {
            List<V2TIMMessage> msg = new ArrayList<>();
            ConversationManager.insertLocalMessage(Constant.CUSTOM_MESSAGE_LOCAL_TIME, false, new V2TIMValueCallback<V2TIMMessage>() {
                @Override
                public void onSuccess(V2TIMMessage v2TIMMessage) {
                    msg.add(v2TIMMessage);
                    msg.add(message);
                    refreshChatList(msg, false);
                }

                @Override
                public void onError(int code, String desc) {
                    printD("ErrorCode=" + code + ",desc=" + desc);
                }
            });
        } else {
            refreshChatList(message, false);
        }
    }

    @Subscribe
    public void voiceSendSuccess(VoiceSendSuccessEvent event) {
        BaseChatEvent<VoiceSendSuccessEvent> chatEvent = new BaseChatEvent<>(event);
        processSendMessage("【语音】", Constant.CUSTOM_MESSAGE_SOUND, chatEvent);
    }

    @Subscribe
    public void giftSendSuccess(GiftSendSuccessEvent event) {
        BaseChatEvent<GiftSendSuccessEvent> chatEvent = new BaseChatEvent<>();
        chatEvent.setEvent(event);
        processSendMessage("【礼物】", Constant.CUSTOM_MESSAGE_GIFT, chatEvent);
    }

    @Subscribe
    public void giftEffectShow(GiftSendEvent event) {
//        showToast("展示礼物效果");
        //第一个过来 size=0,添加进来，然后播放，播放完毕移除第一个
        if (svgaSource.size() >= 1) {
            svgaSource.add(event.getEffects());
        } else {
            svgaSource.add(event.getEffects());
            ConversationManager.playSVGA(this, mSVGAPlayer, event.getEffects());
        }
//        SVGAParser svgaParser = new SVGAParser(this);
//        SVGAParser.ParseCompletion parseCompletion = new SVGAParser.ParseCompletion() {
//
//            @Override
//            public void onError() {
//
//            }
//
//            @Override
//            public void onComplete(@NonNull SVGAVideoEntity svgaVideoEntity) {
//                svgaVideoEntity.setAntiAlias(true);
//                mSVGAPlayer.setVideoItem(svgaVideoEntity);
//                mSVGAPlayer.startAnimation();
//
//           }
//        };
//        String effects = event.getEffects();
//        if (effects.startsWith("http://") || effects.startsWith("https://")) {
//            try {
//                svgaParser.decodeFromURL(new URL(effects), parseCompletion);
//            } catch (MalformedURLException e) {
//                e.printStackTrace();
//            }
//        }
    }

    @Subscribe
    public void videoCallConnectFailed(VideoCallOverEvent event) {
        List<V2TIMMessage> msg = new ArrayList<>();
        ConversationManager.insertLocalMessage(event.getMsgContent(), new V2TIMValueCallback<V2TIMMessage>() {
            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
                msg.add(v2TIMMessage);
                refreshChatList(msg, true);
            }

            @Override
            public void onError(int code, String desc) {

            }
        });

    }

    private void processSendMessage(String content, String type, BaseChatEvent event) {
        if (ConversationManager.shouldInsertTime()) {
            List<V2TIMMessage> msg = new ArrayList<>();
            ConversationManager.insertLocalMessage(Constant.CUSTOM_MESSAGE_LOCAL_TIME, true, new V2TIMValueCallback<V2TIMMessage>() {
                @Override
                public void onSuccess(V2TIMMessage v2TIMMessage) {
                    msg.add(v2TIMMessage);
                }

                @Override
                public void onError(int code, String desc) {

                }
            });
            ConversationManager.sendMessage(content, type, event, new V2TIMSendCallback<V2TIMMessage>() {
                @Override
                public void onProgress(int progress) {

                }

                @Override
                public void onError(int code, String desc) {
                    hideLoading();
                    printD("code=" + code + ",desc=" + desc);
//                    showToast("发送失败ErrCode:" + code + ",msg:" + desc);
//                    if (code == 120009) {
////                        showNeedCharge();
//                    }
                    if ("您的余额不足".equals(desc)) {
                        showNeedCharge();
                    }
                }

                @Override
                public void onSuccess(V2TIMMessage v2TIMMessage) {
                    hideLoading();
//                printD(content + "发送成功");
                    newestV2TIMMessage = v2TIMMessage;
                    msg.add(v2TIMMessage);
                    refreshChatList(msg, true);
                    LastChatEvent lastChatEvent = new LastChatEvent();
                    lastChatEvent.setUserID(mOtherUserID);
                    EventBus.getDefault().post(lastChatEvent);
//                if (type.equals(Constant.CUSTOM_MESSAGE_PICTURE) || type.equals(Constant.CUSTOM_MESSAGE_SOUND)) {
//                    mPresenter.getAccount();
//                }
                }
            });
        } else {
            ConversationManager.sendMessage(content, type, event, new V2TIMSendCallback<V2TIMMessage>() {
                @Override
                public void onProgress(int progress) {

                }

                @Override
                public void onError(int code, String desc) {
                    hideLoading();
                    printD("code=" + code + ",desc=" + desc);
//                    showToast("发送失败ErrCode:" + code + ",msg:" + desc);
//                    if (code == 120009) {
////                        showNeedCharge();
//                    }
                    if ("您的余额不足".equals(desc)) {
                        showNeedCharge();
                    }
                }

                @Override
                public void onSuccess(V2TIMMessage v2TIMMessage) {
                    hideLoading();
                    newestV2TIMMessage = v2TIMMessage;
//                printD(content + "发送成功");
                    refreshChatList(v2TIMMessage, true);
                    LastChatEvent lastChatEvent = new LastChatEvent();
                    lastChatEvent.setUserID(mOtherUserID);
                    EventBus.getDefault().post(lastChatEvent);
//                if (type.equals(Constant.CUSTOM_MESSAGE_PICTURE) || type.equals(Constant.CUSTOM_MESSAGE_SOUND)) {
//                    mPresenter.getAccount();
//                }
                }
            });
        }

    }

    private CustomMessageBean getCustomMessageBean() {
        CustomMessageBean customMessageBean = new CustomMessageBean();
        CustomMessageBean.DataBean dataBean = new CustomMessageBean.DataBean();
        CustomMessageBean.DataBean.UserBean userBeanOther = new CustomMessageBean.DataBean.UserBean();
        userBeanOther.memberId = mOtherUserID;
        userBeanOther.nickname = mOtherShowName;
        userBeanOther.photo = mOtherFaceUrl;
        CustomMessageBean.DataBean.UserBean userBeanSelf = new CustomMessageBean.DataBean.UserBean();
        userBeanSelf.memberId = mSelfUserID;
        userBeanSelf.nickname = mSelfNickname;
        userBeanSelf.photo = mSelfAvatar;
        userBeanSelf.selfSend = "1";//自己发送
        dataBean.fromUser = userBeanSelf;
        dataBean.toUser = userBeanOther;
        customMessageBean.data = dataBean;
        return customMessageBean;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mOtherUserID = "";
//        mAdapter = null;
//        mRecyclerView = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    if (data != null) {
                        List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                        LocalMedia localMedia1 = localMedia.get(0);
                        String path = localMedia1.getPath();
//                        showToast("path=" + path);
                        int cropImageWidth = localMedia1.getCropImageWidth();
                        int cropImageHeight = localMedia1.getCropImageHeight();
                        int width = localMedia1.getWidth();
                        int height = localMedia1.getHeight();
                        printD("filePath=" + path);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            path = PathUtils.getPath(ChatActivity.this, Uri.parse(path));
                        }
                        if (localMedia1.isCompressed()) {
                            path = localMedia1.getCompressPath();
                        }
                        showLoading();
                        printD("filePath=" + path);
                        if (aliUploadUtils != null) {
                            aliUploadUtils.upLoadFile(path, new FileUploadCallback() {
                                @Override
                                public void onFailure(String str) {
                                    showToast("上传失败" + str);
                                    hideLoading();
                                }

                                @Override
                                public void onSuccess(Object paramRequestString, String filePath) {
                                    if (TextUtils.isEmpty(filePath)) {
                                        hideLoading();
                                        return;
                                    }
//                                    showToast("filePath=" + filePath);
                                    ImageSendSuccessEvent event = new ImageSendSuccessEvent();
                                    event.setImgUrl(filePath);
                                    event.setWidth(width);
                                    event.setHeight(height);
                                    imageSendSuccess(event);
                                }

                                @Override
                                public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                                    printD("progress=" + currentSize * 1.0 / totalSize);
                                }
                            });
                        }
                    }

                    break;
            }
        }
    }

}
